﻿/*
* CRM_Follow.cs
*
* 功 能： N/A
* 类 名： CRM_Follow
*
* Ver    变更日期             负责人     变更内容
* ───────────────────────────────────
* V1.0  2015-06-23 18:38:21    黄润伟    
*
* Copyright (c) 2015 www.xhdcrm.com   All rights reserved.
*┌──────────────────────────────────┐
*│　版权所有：黄润伟                      　　　　　　　　　　　　　　│
*└──────────────────────────────────┘
*/

using System;
using System.Data;
using System.Web;
using XHD.Common;
using XHD.Controller;

namespace XHD.Server
{
    public class CRM_Follow
    {
        public static BLL.CRM_Follow follow = new BLL.CRM_Follow();
        public static Model.CRM_Follow model = new Model.CRM_Follow();

        public HttpContext Context;
        public int emp_id;
        public string emp_name;
        public Model.hr_employee employee;
        public HttpRequest request;
        public string uid;


        public CRM_Follow()
        {
        }

        public CRM_Follow(HttpContext context)
        {
            Context = context;
            request = context.Request;

            var userinfo = new User_info();
            employee = userinfo.GetCurrentEmpInfo(context);

            emp_id = employee.ID;
            emp_name = PageValidate.InputText(employee.name, 50);
            uid = PageValidate.InputText(employee.uid, 50);
        }

        public void save()
        {
            var customer = new BLL.CRM_Customer();

            model.Follow = PageValidate.InputText(request["T_follow"], 4000);

            string cid = PageValidate.InputText(request["cid"], 50);
            if (PageValidate.IsNumber(cid))
                model.Customer_id = int.Parse(cid);

            string followtype = PageValidate.InputText(request["T_followtype_val"], 50);
            if (PageValidate.IsNumber(followtype))
                model.Follow_Type_id = int.Parse(followtype);

            string contact = PageValidate.InputText(request["T_contact_val"], 50);
            if (PageValidate.IsNumber(contact))
                model.Contact_id = int.Parse(contact);

            string aim = PageValidate.InputText(request["T_followaim_val"], 50);
            if (PageValidate.IsNumber(aim))
                model.Follow_aim_id = int.Parse(aim);

            string fid = PageValidate.InputText(request["fid"], 50);
            if (PageValidate.IsNumber(fid))
            {
                DataSet ds = follow.GetList("id=" + int.Parse(fid));
                DataRow dr = ds.Tables[0].Rows[0];
                model.id = int.Parse(fid);

                follow.Update(model);

                //最后跟进
                customer.UpdateLastFollow(model.Customer_id.ToString());

                //日志
                var log = new sys_log();
                int UserID = emp_id;
                string UserName = emp_name;
                string IPStreet = request.UserHostAddress;
                string EventTitle = dr["Customer_name"].ToString();
                string EventType = "客户跟进修改";
                int EventID = model.id;
                string Log_Content = null;

                if (dr["Follow"].ToString() != request["T_follow"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "跟进内容", dr["Follow"], request["T_follow"]);

                if (dr["Follow_Type"].ToString() != request["T_followtype"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "跟进类型", dr["Follow_Type"], request["T_followtype"]);

                if (dr["Contact"].ToString() != request["T_contact"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "联系人", dr["Contact"], request["T_contact"]);

                if (dr["Follow_aim"].ToString() != request["T_followaim"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "跟进目的", dr["Follow_aim"], request["T_followaim"]);

                if (!string.IsNullOrEmpty(Log_Content))
                    log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, Log_Content);
            }
            else
            {
                model.isDelete = 0;
                model.employee_id = emp_id;
                model.department_id = employee.d_id;
                model.Follow_date = DateTime.Now;

                int customerid = follow.Add(model);

                //最后跟进
                customer.UpdateLastFollow(model.Customer_id.ToString());
            }
        }

        public string form(string id)
        {
            string dt;
            if (PageValidate.IsNumber(id))
            {
                DataSet ds = follow.GetList("id=" + id + DataAuth());
                dt = DataToJson.DataToJSON(ds);
            }
            else
            {
                dt = "{}";
            }

            return (dt);
        }

        //del
        public string del(int id)
        {
            DataSet ds = follow.GetList("id=" + id);

            bool canedel = true;
            if (uid != "admin")
            {
                var dataauth = new GetDataAuth();
                string txt = dataauth.GetDataAuthByid("2", "Sys_del", emp_id);

                string[] arr = txt.Split(':');
                switch (arr[0])
                {
                    case "none":
                        canedel = false;
                        break;
                    case "my":
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            if (ds.Tables[0].Rows[i]["employee_id"].ToString() == arr[1])
                                canedel = true;
                            else
                                canedel = false;
                        }
                        break;
                    case "dep":
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            if (ds.Tables[0].Rows[i]["dep_id"].ToString() == arr[1])
                                canedel = true;
                            else
                                canedel = false;
                        }
                        break;
                    case "all":
                        canedel = true;
                        break;
                }
            }
            if (canedel)
            {
                bool isdel = follow.Delete(int.Parse(request["id"]));
                //context.Response.Write("{success:success}");
                if (isdel)
                {
                    //日志
                    string EventType = "跟进删除";

                    int UserID = emp_id;
                    string UserName = emp_name;
                    string IPStreet = request.UserHostAddress;
                    int EventID = id;
                    string EventTitle = ds.Tables[0].Rows[0]["Customer_name"].ToString();

                    var log = new sys_log();

                    string Log_Content = null;

                    Log_Content += string.Format("【{0}】{1}", "跟进内容", ds.Tables[0].Rows[0]["Follow"]);

                    log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, Log_Content);

                    return ("true");
                }
                return ("false");
            }
            return ("delfalse");
        }

        //serch
        public string grid()
        {
            int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " id ";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = " desc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total;

            string serchtxt = "1=1";

            if (!string.IsNullOrEmpty(request["customer_id"]))
                serchtxt += " and Customer_id=" + int.Parse(request["customer_id"]);

            if (!string.IsNullOrEmpty(request["company"]))
                serchtxt += $" and Customer_id in (select id from CRM_Customer where Customer like N'%{ PageValidate.InputText(request["company"], 255)}%')";

            if (!string.IsNullOrEmpty(request["department"]))
                serchtxt += " and department_id = " + int.Parse(request["department_val"]);

            if (!string.IsNullOrEmpty(request["employee"]))
                serchtxt += " and employee_id = " + int.Parse(request["employee_val"]);

            if (!string.IsNullOrEmpty(request["followtype"]))
                serchtxt += " and Follow_Type_id = " + int.Parse(request["followtype_val"]);

            if (!string.IsNullOrEmpty(request["startdate"]))
                serchtxt += " and Follow_date >= '" + PageValidate.InputText(request["startdate"], 255) + "'";

            if (!string.IsNullOrEmpty(request["enddate"]))
            {
                DateTime enddate = DateTime.Parse(request["enddate"]).AddHours(23).AddMinutes(59).AddSeconds(59);
                serchtxt += " and Follow_date  <= '" + enddate + "'";
            }

            if (!string.IsNullOrEmpty(request["startdate_del"]))
                serchtxt += " and Delete_time >= '" + PageValidate.InputText(request["startdate_del"], 255) + "'";

            if (!string.IsNullOrEmpty(request["enddate_del"]))
            {
                DateTime enddate = DateTime.Parse(request["enddate_del"]).AddHours(23).AddMinutes(59).AddSeconds(59);
                serchtxt += " and Delete_time  <= '" + enddate + "'";
            }
            if (!string.IsNullOrEmpty(request["T_smart"]))
            {
                if (request["T_smart"] != "输入关键词智能搜索跟进内容")
                    serchtxt += " and Follow like N'%" + PageValidate.InputText(request["T_smart"], 255) + "%'";
            }
            //权限
            serchtxt += DataAuth();

            DataSet ds = follow.GetList(PageSize, PageIndex, serchtxt, sorttext, out Total);

            string dt = GetGridJSON.DataTableToJSON1(ds.Tables[0], Total);
            return (dt);
        }

        public string Compared_follow()
        {
            string year1 = PageValidate.InputText(request["year1"], 50);
            string year2 = PageValidate.InputText(request["year2"], 50);
            string month1 = PageValidate.InputText(request["month1"], 50);
            string month2 = PageValidate.InputText(request["month2"], 50);

            DataSet ds = follow.Compared_follow(year1, month1, year2, month2);

            string dt = GetGridJSON.DataTableToJSON(ds.Tables[0]);
            return (dt);
        }

        public string Compared_empcusfollow()
        {
            string idlist = PageValidate.InputText(request["idlist"], int.MaxValue);
            string year1 = PageValidate.InputText(request["year1"], 50);
            string year2 = PageValidate.InputText(request["year2"], 50);
            string month1 = PageValidate.InputText(request["month1"], 50);
            string month2 = PageValidate.InputText(request["month2"], 50);

            if (idlist.Length < 1)
                idlist = "0";

            string[] pid = idlist.Split(';');
            string pidlist = "";
            for (int i = 0; i < pid.Length; i++)
            {
                int j = pid[i].IndexOf('p');
                if (j != -1)
                {
                    pidlist += pid[i].Replace("p", "") + ",";
                }
            }
            pidlist += "0";

            var post = new BLL.hr_post();
            DataSet dspost = post.GetList("id in(" + pidlist + ")");

            string emplist = "(";

            for (int i = 0; i < dspost.Tables[0].Rows.Count; i++)
            {
                emplist += dspost.Tables[0].Rows[i]["emp_id"] + ",";
            }
            emplist += "0)";

            //context.Response.Write(emplist);

            DataSet ds = follow.Compared_empcusfollow(year1, month1, year2, month2, emplist);

            string dt = GetGridJSON.DataTableToJSON(ds.Tables[0]);
            return (dt);
        }

        public string emp_cusfollow()
        {
            string idlist = PageValidate.InputText(request["idlist"], int.MaxValue);
            string syear = request["syear"];

            if (idlist.Length < 1)
                idlist = "0";

            string[] pid = idlist.Split(';');
            string pidlist = "";
            for (int i = 0; i < pid.Length; i++)
            {
                int j = pid[i].IndexOf('p');
                if (j != -1)
                {
                    pidlist += pid[i].Replace("p", "") + ",";
                }
            }
            pidlist += "0";

            var post = new BLL.hr_post();
            DataSet dspost = post.GetList("id in(" + pidlist + ")");

            string emplist = "(";

            for (int i = 0; i < dspost.Tables[0].Rows.Count; i++)
            {
                emplist += dspost.Tables[0].Rows[i]["emp_id"] + ",";
            }
            emplist += "0)";

            //context.Response.Write(emplist);

            DataSet ds = follow.report_empfollow(int.Parse(syear), emplist);

            string dt = GetGridJSON.DataTableToJSON(ds.Tables[0]);
            return (dt);
        }

        private string DataAuth()
        {
            //权限            
            string uid = employee.uid;
            string returntxt = "";

            if (uid != "admin")
            {
                {
                    var dataauth = new GetDataAuth();
                    string txt = dataauth.GetDataAuthByid("2", "Sys_view", emp_id);

                    string[] arr = txt.Split(':');
                    switch (arr[0])
                    {
                        case "none":
                            returntxt = " and 1=2 ";
                            break;
                        case "my":
                            returntxt = " and  Employee_id=" + arr[1];
                            break;
                        case "dep":
                            if (string.IsNullOrEmpty(arr[1]))
                                returntxt = " and  Employee_id=" + int.Parse(uid);
                            else
                                returntxt = " and  Department_id=" + arr[1];
                            break;
                        case "depall":
                            var dep = new BLL.hr_department();
                            DataSet ds = dep.GetAllList();
                            string deptask = GetTasks.GetDepTask(int.Parse(arr[1]), ds.Tables[0]);
                            string intext = arr[1] + "," + deptask;
                            returntxt = " and  Department_id in (" + intext.TrimEnd(',') + ")";
                            break;
                    }
                }
            }
            return returntxt;
        }
    }
}